package com.net.test.controller;

import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.net.test.common.PagingUtil;
import com.net.test.common.PublicString;
import com.net.test.common.TestLoginUtil;
import com.net.test.service.TService;
import com.net.test.utility.FileManager;
import com.net.test.utility.SecurityGuide;
import com.net.test.vo.PageInfoVO;
import com.net.test.vo.TVO;


@Controller
public class TController {
	
	
	@Autowired
	TService tService;
	@RequestMapping(value = "/tLogout.ncb", method = {RequestMethod.GET,RequestMethod.POST})
	public String tLogout(Locale locale, Model model, HttpServletRequest request) throws Exception {
		TestLoginUtil loginUtil = new TestLoginUtil();
		loginUtil.logout(request);
		return "tLogin";
		
	}
	@RequestMapping(value = "/tLogin.ncb", method = {RequestMethod.GET,RequestMethod.POST})
	public String tLogin(Locale locale, Model model) throws Exception {
		
		return "tLogin";
		
	}
	@RequestMapping(value = "/tmemView.ncb", method = {RequestMethod.GET,RequestMethod.POST})
	public String tmemview(Locale locale, Model model) throws Exception {
		
		return "tmemView";
		
	}
	@RequestMapping(value = "/tlogInsert.ncb", method = {RequestMethod.GET,RequestMethod.POST})
	public String tmemInsert(Locale locale, Model model, HttpServletRequest request, TVO tvo) throws Exception{		
		
		int result = tService.insertData1("testMapper.tlogInsert", tvo);	
		
		model.addAttribute("result", result+"");
		
		return "tLogin";		
	}
	
	@RequestMapping(value = "/exceldown.ncb", method = {RequestMethod.GET, RequestMethod.POST})
	public String exceldown(Locale locale, Model model, HttpServletRequest request,HttpServletResponse response, PageInfoVO pageInfoVO,TVO tvo) throws Exception{
		
		
		
		response.setHeader("Content-Disposition","attachment;filename=member.xls");
	    response.setHeader("Content-Description", "JSP Generated Data");
	    response.setContentType("application/vnd.ms-excel");
	    
	    return "tlogView";

	}
	@RequestMapping(value = "/tlogView.ncb", method = {RequestMethod.GET, RequestMethod.POST})
	public String tLogView(Locale locale, Model model, HttpServletRequest request,HttpServletResponse response, PageInfoVO pageInfoVO,TVO tvo) throws Exception{
			
		TestLoginUtil loginUtil = new TestLoginUtil();		
		
		String login = loginUtil.loginCheck(request);
		
		if(login==null){
			return "tLogin";
		}
		else if(login != null && login.equals("id")){
			//id만 맞는경우 비번틀림
		}
		else if(login != null && login.equals("login"));{
			//로그인 성공
		}
		//리스트 토탈 가져오기		
		
		int m_board_total_cnt = tService.m_board_total_cnt("testMapper.m_board_total_cnt", tvo);
		
		pageInfoVO.setTotal_record(m_board_total_cnt);//필수
		pageInfoVO.setPage_per_record_cnt(5); //기본
		pageInfoVO.setGroup_per_page_cnt(5);//기본
		
		pageInfoVO = PagingUtil.PagingCheck(pageInfoVO);
		
		tvo.setRecord_start_no(pageInfoVO.getRecord_start_no());
		tvo.setRecord_end_no(pageInfoVO.getRecord_end_no());
		
		
		List<TVO> list = (List<TVO>)tService.m_board_list("testMapper.tselectBoard2", tvo);
	
		model.addAttribute("tvo", tvo);
		model.addAttribute("list", list);
		model.addAttribute("pageInfoVO", pageInfoVO	);	
		

		
		
		return "tlogView";

	}			

	@RequestMapping(value = "/likeUpdate.ncb", method = {RequestMethod.GET, RequestMethod.POST})
	public String likeUpdate(Locale locale, Model model, HttpServletRequest request,TVO tvo ) throws Exception{				
		
		int resInt = (Integer)tService.likeCount("testMapper.tboardLikeCount", tvo);
		
		TVO view = (TVO)tService.ViewData("testMapper.tboardView", tvo);
		
		model.addAttribute("view",view);
		
		
		return "tboardView";
		
	}
	@RequestMapping(value = "/tWrite.ncb", method = {RequestMethod.GET, RequestMethod.POST})
	public String tWrite(Locale locale, Model model, HttpServletRequest request,TVO tvo ) throws Exception{		
		
		//TVO view = (TVO)tService.getViewDataOne2("testMapper.tloginView2", tvo);	
		
		//model.addAttribute("view",tvo);
//		String re = request.getParameter("re");
//		
//		//글쓰기 화면 처음일 경우
//		if(re == null){
//			re = "n";
//		} 	
//		
//		model.addAttribute("re", re);
		return "tWrite";
		
	}
	
	@RequestMapping(value = "/tboardinsert.ncb", method = {RequestMethod.GET,RequestMethod.POST})
	public String tboardInsert(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response, TVO tvo) throws Exception{
		
		MultipartFile file =  tvo.getFile();
		
		String realPath = request.getRealPath("/");
		String savePath = realPath + PublicString.uploadFolder;
		
		System.out.println("파일 저장되는 경로 : " + savePath);

		FileManager fm = new FileManager();
		String newFileName = fm.doFileUpload(file.getBytes(), file.getOriginalFilename(), savePath);
		
		System.out.println("원래 파일이름 : " + file.getOriginalFilename());
		System.out.println("새로 생성된 파일이름 : " + newFileName);
		tvo.setOrg_name(file.getOriginalFilename());
		tvo.setNew_name(newFileName);
		
		//Path는 주로 DB에 저장은 잘 안합니다.  할때도 있음
		tvo.setFile_path(savePath);
		
		int result = tService.insertData1("testMapper.tmemInsert", tvo);
		
		//TVO view = (TVO)tService.getViewDataOne2("testMapper.tloginView2", tvo);
		
		//List<TVO> list = (List<TVO>)tService.selectList("testMapper.tselectBoard2", tvo);
		//System.out.println(list.size());
		
		//model.addAttribute("view", view);
		//model.addAttribute("view", tvo);
		//model.addAttribute("list", list);
		//System.out.println(list.size());
		//response.sendRedirect("/tlogView.ncb");
		//tLogView(locale, model, request);
		
		model.addAttribute("result", result+"");		
		//파일삭제 
		String tempFile[] = request.getParameterValues("tempFile");
		if(tempFile != null && tempFile.length > 0){
			for (int i = 0; i < tempFile.length; i++) {
				fm.doFileDelete(tempFile[i].trim(), realPath + PublicString.uploadTempFolder);
			}
		}	
		
		return "tWrite";		

	}
	@RequestMapping(value = "/tboardView.ncb", method = {RequestMethod.GET,RequestMethod.POST})
	public String tboardView(Locale locale, Model model, HttpServletRequest request ,TVO tvo) throws Exception{		
//	   String title = request.getParameter("title");
//		String contents= request.getParameter("contents");
//		
//		TVO tvo = new TVO();
//		tvo.setTitle(title);
//		System.out.println(title);
//		tvo.setContents(contents);
//		System.out.println(contents);	
		//System.out.println("11");		
		//조회수 증가
		int resInt = (Integer)tService.hitCount("testMapper.tboardHitCount", tvo);
		
		TVO view = (TVO)tService.ViewData("testMapper.tboardView", tvo);
		System.out.println(tvo);
//		List<TVO> list = (List<TVO>)tService.m_board_list("testMapper.tselectBoard2", tvo);
//		
//		model.addAttribute("list", list);
//		
		model.addAttribute("view", view);
		System.out.println(tvo);
		
		
		
		//tLogView(locale, model, request);
		
		return "tboardView";		
	}
	@RequestMapping(value = "/tboardEdit.ncb", method = {RequestMethod.GET,RequestMethod.POST})
	public String tboardEdit(Locale locale, Model model, HttpServletRequest request, TVO tvo) throws Exception{
		
		TVO view = (TVO)tService.ViewData("testMapper.tboardView", tvo);
		
		model.addAttribute("edit", view);
		
		System.out.println(view);
		return "tboardEdit";		
		
	}
	@RequestMapping(value = "/tboardUpdate.ncb", method = {RequestMethod.GET, RequestMethod.POST})
	public String tboardUpdate(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response, TVO tvo)throws Exception{
		
		int result = tService.updateData2("testMapper.tboardUpdate", tvo);
//		List<TVO> list = (List<TVO>)tService.m_board_list("testMapper.tselectBoard2", tvo);
//		model.addAttribute("list",list);
		model.addAttribute("result", result+"");
		//model.addAttribute("view", tvo);
		//tLogView(locale, model, request);
		 
 		return "tboardEdit";
	}
	@RequestMapping(value = "/tboardDel.ncb", method = {RequestMethod.GET, RequestMethod.POST})
	public String tboardDel(Locale locale, Model model, HttpServletRequest request, TVO tvo)throws Exception{
		
		
		int result = tService.deleteData1("testMapper.tboardDel",tvo);
		
		model.addAttribute("result", result+"");
		//tLogView(locale, model, request);
		return "tboardView";		
	}
	@RequestMapping(value = "/tmemEdit.ncb", method = {RequestMethod.GET, RequestMethod.POST})
	public String tmemEdit(Locale locale, Model model, HttpServletRequest request, TVO tvo)throws Exception{
		
		
		
		
		model.addAttribute("edit", tvo);
		System.out.println(tvo);
		
		return "tmemEdit";
	}
	
	@RequestMapping(value = "/tmemUpdate.ncb", method = {RequestMethod.GET, RequestMethod.POST})
	public String tmemUpdate(Locale locale, Model model, HttpServletRequest request, TVO tvo)throws Exception{
		
//		String upid = request.getParameter("upid");
//		String id = request.getParameter("id");
//		String name = request.getParameter("name");
//		String password = request.getParameter("password");
//		
//		TVO tvo = new TVO();
//		
//		tvo.setSeq(upid);		
//		tvo.setId(id);		
//		tvo.setName(name);		
//		tvo.setPassword(password);		
		
		int result = tService.updateData3("testMapper.tmemUpdate", tvo);		
		model.addAttribute("result",result+"");
		System.out.println(tvo);		
		
		return "tlogView";
	}	

	
	
	/**
	 * 원래는 따로 공통으로 클래스 만들어서 해야됨
	 * @param locale
	 * @param model
	 * @param request
	 * @param response
	 * @param tvo
	 * @throws Exception
	 */
	@RequestMapping(value = "/downLoad.ncb", method = {RequestMethod.GET,RequestMethod.POST})
	public void downLoad(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response, TVO tvo) throws Exception{
		TVO view = (TVO)tService.ViewData("testMapper.tboardView", tvo);
		
		FileManager fm = new FileManager();
		
		boolean result = fm.doFileDownload(view.getNew_name(), view.getOrg_name(), view.getFile_path(), response);
		System.out.println(result);
	}
	
	@RequestMapping(value = "/viewImage.ncb", method = {RequestMethod.GET, RequestMethod.POST})
	public String viewImage(Locale locale, Model model, HttpServletRequest request, TVO tvo)throws Exception{
		
		MultipartFile file =  tvo.getFile();
		String mimeType = null;
		
		
		//허용되는 마임타입 image/jpeg 
		mimeType = SecurityGuide.securityMimeType(file.getBytes());
		
		if(!(mimeType.indexOf("image") > -1)){
			model.addAttribute("newFileName","mimeTypeError");
			return "responseMsg";
		}
		
		
		
		String realPath = request.getRealPath("/");
		String savePath = realPath + PublicString.uploadTempFolder;
		

		
		System.out.println("파일 저장되는 경로 : " + savePath);

		FileManager fm = new FileManager();
		String newFileName = fm.doFileUpload(file.getBytes(), file.getOriginalFilename(), savePath);
		
		System.out.println("원래 파일이름 : " + file.getOriginalFilename());
		System.out.println("새로 생성된 파일이름 : " + newFileName);
		tvo.setOrg_name(file.getOriginalFilename());
		tvo.setNew_name(newFileName);		
		
	
		model.addAttribute("newFileName",newFileName);
		return "responseMsg";
	}
}
